package com.roc.template.websocket.task;

import com.alibaba.fastjson.JSON;
import com.roc.template.base.PageBean;
import com.roc.template.mongo.model.RemoteUser;
import com.roc.template.mongo.service.impl.RemoteUserServiceImpl;
import com.roc.template.mongo.vo.RemoteUserVo;
import com.roc.template.cloud.util.HttpClientUtils;
import com.roc.template.websocket.SocketBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component
public class DCAutoTask {

    Logger logger = LoggerFactory.getLogger(DCAutoTask.class);

    @Resource
    private RemoteUserServiceImpl remoteUserService;

    public static final Integer PAGE_SIZE = 500;

//	@Scheduled(cron = "*/35 * * * * ?")
    public void sysTask() {

        long nowTime = System.currentTimeMillis();
        RemoteUserVo remoteUserVo = new RemoteUserVo();
        remoteUserVo.setPageNum(1);
        remoteUserVo.setPageSize(PAGE_SIZE);
        PageBean<RemoteUser> remoteUserPageBean = remoteUserService.pageQuery(remoteUserVo);
        List<RemoteUser> list = remoteUserPageBean.getList();
        pushShutRemote(nowTime, list);
        for(int i=2;i<=remoteUserPageBean.getPages();i++) {
            remoteUserVo.setPageNum(i);
            remoteUserPageBean = remoteUserService.pageQuery(remoteUserVo);
            list = remoteUserPageBean.getList();
            pushShutRemote(nowTime, list);
        }
    }

    private void pushShutRemote(long nowTime, List<RemoteUser> list) {
        for (RemoteUser remoteUser : list) {
            //超过30秒没有刷新时间则推送关闭远程的socket
            long createTime = nowTime - remoteUser.getCreateRefreshTime().getTime();
            logger.info("createTime"+ createTime);
            long toTime = nowTime - remoteUser.getToRefreshTime().getTime();
            logger.info("toTime"+ createTime);
            if(nowTime-remoteUser.getCreateRefreshTime().getTime()>35000) {
                push(remoteUser);
            }
            if(nowTime-remoteUser.getToRefreshTime().getTime()>35000) {
                push(remoteUser);
            }
        }
    }

    private void push(RemoteUser remoteUser) {
        SocketBean socketBean = new SocketBean();
        socketBean.setEvent(3);
//
        Map<String, Object> param = new HashMap<>();
        param.put("fromSystem", "remote");
        param.put("userIds", new String[]{remoteUser.getCreatorWbUserId(), remoteUser.getToWbUserId()});
        param.put("msg", socketBean);
        remoteUserService.delete(remoteUser.getId());
        String post = HttpClientUtils.post("https://dev.kdweibo.cn/xtinterface/extSys/sendNotify", JSON.toJSONString(param));
        logger.info("超时推送关闭远程的socket：" + JSON.toJSONString(param));
    }
}

